/*
 * Copyright 2002-2007 the original author or authors.
 */
package com.lianzt.factory;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import android.util.Log;

import com.lianzt.util.Base64;

/**
 * 加、解密工具
 * 
 * @author lianzt
 */
public class AESFactory {

	private static byte[] KEY = "1234123412341234".getBytes();
	private static Cipher cipher;
	private static SecretKeySpec skeySpec;
	private static final String TAG = "AESFactory";

	static {
		init();
	}

	private static void init() {
		try {
			skeySpec = new SecretKeySpec(KEY, "AES");
			cipher = Cipher.getInstance("AES");
		} catch (NoSuchAlgorithmException e) {
			Log.e(TAG, "AES error : ", e);
		} catch (NoSuchPaddingException e) {
			Log.e(TAG, "AES error : ", e);
		}
	}

	/**
	 * 设置密钥
	 * 
	 * @param bytes
	 */
	public static void setKey(byte[] bytes) {
		if (bytes == null) {
			Log.w(TAG, "密钥设置失败，参数为null，使用默认密钥");
			return;
		}
		if (bytes.length != 16) {
			Log.w(TAG, "密钥设置失败，长度不为128位，使用默认密钥");
			return;
		}
		KEY = bytes;
		init();
	}

	public static byte[] encrypt(byte[] src) throws Exception {
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		return cipher.doFinal(src);
	}

	public static byte[] decrypt(byte[] src) throws Exception {
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		return cipher.doFinal(src);
	}

	public static String encryptString(String src) throws Exception {
		byte[] temp = encrypt(src.getBytes("UTF-8"));
		return Base64.encode(temp);
	}

	public static String decryptString(String src) throws Exception {
		byte[] temp = decrypt(Base64.decode(src));
		return new String(temp, "UTF-8");
	}
}
